﻿using System;
using System.Text;
using System.Net;
using Newtonsoft.Json;

namespace xrwang.weixin.PublicAccount
{
    /// <summary>
    /// 服务器地址
    /// </summary>
    public class ServerAddresses
    {
        /// <summary>
        /// 获取微信服务器地址列表的地址
        /// </summary>
        private const string urlGetServerAddresses = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token={0}";
        /// <summary>
        /// 获取微信服务器地址列表的http方法
        /// </summary>
        private const string httpMethodForGettingServerAddresses = WebRequestMethods.Http.Get;

        /// <summary>
        /// 地址数组
        /// </summary>
        public string[] ip_list { get; set; }

        internal ServerAddresses(string[] _ip_list)
        {
            ip_list = _ip_list;
        }

        /// <summary>
        /// 返回地址列表字符串，每个地址间用逗号分隔
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            if (ip_list != null && ip_list.Length > 0)
            {
                foreach (string ip in ip_list)
                    sb.AppendFormat("{0},", ip);
                sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 返回JSON字符串
        /// </summary>
        /// <returns></returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }

        /// <summary>
        /// 从JSON字符串解析服务器地址
        /// </summary>
        /// <param name="json">JSON字符串</param>
        /// <returns>返回服务器地址</returns>
        internal static ServerAddresses ParseFromJson(string json)
        {
            var sa = JsonConvert.DeserializeAnonymousType(json, new { ip_list = new string[1] });
            return new ServerAddresses(sa.ip_list);
        }

        /// <summary>
        /// 尝试从JSON字符串解析服务器地址
        /// </summary>
        /// <param name="json">JSON字符串</param>
        /// <param name="msg">如果解析成功，返回服务器地址；否则，返回null。</param>
        /// <returns></returns>
        internal static bool TryParseFromJson(string json, out ServerAddresses addresses)
        {
            bool success = false;
            addresses = null;
            try
            {
                addresses = ParseFromJson(json);
                success = true;
            }
            catch { }
            return success;
        }

        /// <summary>
        /// 获取微信服务器的地址列表
        /// </summary>
        /// <param name="msg">服务器返回的错误提示。</param>
        /// <returns>返回微信服务器的地址列表</returns>
        public static ServerAddresses Get(out ErrorMessage msg)
        {
            msg = ErrorMessage.Exception;
            ServerAddresses addresses = null;
            AccountInfo account = AccountInfoCollection.First;
            if (account == null)
                return null;
            AccessToken token = AccessToken.Get(account.UserName);
            if (token == null)
                return null;
            string url = string.Format(urlGetServerAddresses, token.access_token);
            string result;
            HttpHelper.Request(url, out result, httpMethodForGettingServerAddresses, string.Empty);
            if (ErrorMessage.IsErrorMessage(result))
                msg = ErrorMessage.Parse(result);
            else
            {
                try
                {
                    addresses = ServerAddresses.ParseFromJson(result);
                    msg = ErrorMessage.Success;
                }
                catch (Exception e)
                {
                    msg = new ErrorMessage(e);
                }
            }
            return addresses;
        }
    }
}
